<?php

namespace App\Http\Controllers\api;

use App\Models\Commission;
use App\Models\Setting;
use App\Models\User;
use App\Services\Wallet\UserWalletService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PopularizeController extends BaseController
{
    public function summary(Request $request)
    {
        $userId = auth('jwt')->id();
        $today = Carbon::today();
        $yesterday = Carbon::yesterday();

        $totalInvites = User::query()->where('parent_id', $userId)->count();
        $todayInvites = User::query()->where('parent_id', $userId)
            ->whereDate('created_at', $today)
            ->count();
        $yesterdayInvites = User::query()->where('parent_id', $userId)
            ->whereDate('created_at', $yesterday)
            ->count();

        $totalCommissions = Commission::query()->where('user_id', $userId)->sum('user_money');

        // $exchangeRate = Setting::get('exchange_rate');
        // $totalCommissions = sprintf('%.2f', UserWalletService::getWithdrawableCoins(auth()->user()) / $exchangeRate);

        $todayCommissions = Commission::query()->where('user_id', $userId)
            ->whereDate('child_user_withdraw_at', $today)
            ->sum('user_money');
        $yesterdayCommissions = Commission::query()->where('user_id', $userId)
            ->whereDate('child_user_withdraw_at', $yesterday)
            ->sum('user_money');


        return $this->success([
            'fans' => $totalInvites,
            'invites' => [
                'total' => $totalInvites,
                'today' => $todayInvites,
                'yesterday' => $yesterdayInvites,
            ],
            'commissions' => [
                'total' => $totalCommissions,
                'today' => $todayCommissions,
                'yesterday' => $yesterdayCommissions,
            ],
        ]);
    }

    public function disciples(Request $request)
    {
        $userId = auth('jwt')->id();
        $totalInvites = User::query()->where('parent_id', $userId)->count();
        $totalCommissions = Commission::query()->where('user_id', $userId)->sum('user_money');

        $childIds = User::query()->where('parent_id', $userId)->select('id')->pluck('id')->toArray();
        $disciples = DB::table('users')
            ->leftJoin('commissions', 'users.id', '=', 'commissions.child_user_id')
            ->select(
                'users.uuid',
                'users.nickname',
                'users.avatar',
                DB::raw('SUM(commissions.user_money) as total_commission')
            )
            ->where('commissions.user_id', $userId)
            ->whereIn('users.id', $childIds)
            ->groupBy('commissions.child_user_id', 'users.uuid', 'users.nickname', 'users.avatar')
            ->get();
        foreach ($disciples as &$disciple) {
            if (!$disciple->total_commission) {
                $disciple->total_commission = 0;
            }
        }

        return $this->success([
            'total' => $totalInvites,
            'commissions' => $totalCommissions,
            'disciples' => array_reverse($disciples->toArray()),
        ]);
    }

    public function purse(Request $request)
    {
        /** @var User $user */
        // $user = auth('jwt')->user();
        $userId = auth('jwt')->id();
        // $exchangeRate = Setting::get('exchange_rate');

        $today = Carbon::today();
        $yesterday = Carbon::yesterday();

        // 可提现金额
        // $withdrawable = sprintf('%.2f', UserWalletService::getWithdrawableCoins($user) / $exchangeRate);
        $withdrawable = Commission::query()->where('user_id', $userId)->sum('user_money');
        // 昨日收益
        // $yesterdayIncomes = sprintf('%.2f', UserWalletService::getYesterdayCoins($user) / $exchangeRate);
        $yesterdayIncomes = Commission::query()
            ->where('user_id', $userId)
            ->whereDate('child_user_withdraw_at', $yesterday)
            ->sum('user_money');

        // 今日收益
        // $todayIncomes = sprintf('%.2f', UserWalletService::getTodayCoins($user) / $exchangeRate);
        $todayIncomes = Commission::query()
            ->where('user_id', $userId)
            ->whereDate('child_user_withdraw_at', $today)
            ->sum('user_money');
        // 累计收益
        // $totalIncomes = sprintf('%.2f', UserWalletService::getUserAllCoins($user) / $exchangeRate);
        $totalIncomes = $withdrawable;


        return $this->success([
            'withdrawable' => $withdrawable,
            'incomes' => [
                'yesterday' => $yesterdayIncomes,
                'today' => $todayIncomes,
                'total' => $totalIncomes,
            ],
        ]);
    }

    public function commissions(Request $request)
    {
        $userId = auth('jwt')->id();
        // 总收益
        $totalCommissions = Commission::query()->where('user_id', $userId)->sum('user_money');
        // 推广奖励
        $popularizeAwards = "0.00";
        // 活动补贴
        $activityAwards = "0.00";
        // 邀请新人奖励
        $inviteAwards = $totalCommissions;

        return $this->success([
            'total_commissions' => $totalCommissions,
            'popularize_awards' => $popularizeAwards,
            'activity_awards' => $activityAwards,
            'invite_awards' => $inviteAwards,
        ]);
    }

    public function bills(Request $request)
    {
        $userId = auth('jwt')->id();
        $totalCommissions = 0;

        $earnings = Commission::query()
            ->select(
                DB::raw('DATE(child_user_withdraw_at) as date'),
                DB::raw('SUM(user_money) as total_earnings')
            )
            ->where('user_id', $userId)
            ->groupBy(DB::raw('DATE(child_user_withdraw_at)'))
            ->orderBy('date', 'desc')
            ->get()
            ->keyBy('date');

        $bills = [];
        foreach ($earnings as $earning) {
            $commission = $earning->total_earnings ?? '0.00';
            $bill = [
                'date' => $earning->date,
                'commissions' => $commission,
                'popularize_awards' => "0.00",
                'activity_awards' => "0.00",
                'invite_awards' => $commission,
            ];
            $bills[] = $bill;
            $totalCommissions = sprintf('%.2f', $totalCommissions + $bill['commissions']);
        }

        return $this->success([
            'total_commissions' => $totalCommissions,
            'bills' => $bills,
        ]);
    }

    public function invites(Request $request)
    {
        $userId = auth('jwt')->id();

        $earnings = Commission::query()
            ->with(['child:id,uuid,nickname'])
            ->select(
                'child_user_id', DB::raw('DATE(child_user_withdraw_at) as date'), 'user_money', 'child_user_money'
            )
            ->where('user_id', $userId)
            ->orderBy('date', 'desc')
            ->get();

        $invites = [];
        $withdraws = [];
        foreach ($earnings as $earning) {
            $key = sprintf("%s_%s", $earning->date, $earning->child->uuid);
            $commission = $earning->user_money ?? '0.00';
            $withdraw = $earning->child_user_money ?? '0.00';
            $uuid = $earning->child->uuid ?? '--';
            if (!isset($invites[$key])) {
                $withdraws[$key] = $withdraw;
                $invite = [
                    'date' => $earning->date,
                    'commission' => $commission,
                    'remark' => sprintf("徒弟累计提现%s元", $withdraw),
                    'uuid' => $uuid,
                ];
            } else {
                $item = $invites[$key];
                $withdraws[$key] += $withdraw;
                $invite = [
                    'date' => $item['date'],
                    'commission' => sprintf("%.2f", $item['commission'] + $commission),
                    'remark' => sprintf("徒弟累计提现%s元", $withdraw),
                    'uuid' => $uuid,
                ];
            }
            $invites[$key] = $invite;
        }
        $list = array_values($invites);

        return $this->success([
            'total_commissions' => sprintf('%.2f', array_sum(array_column($list, 'commission'))),
            'invites' => $list,
        ]);
    }

}
